//index.js


var app = getApp()

module.exports = {
  data: {
    detail: [],
    commentfocus: false
  },

  onLoad: function (options) {
    this.setData({
      detail: [],
      commentfocus: false
    });
    wx.setNavigationBarTitle({
      title: '动态详情'
    })
    var id = options.dynamic_id;


    var _this = this;
    var sql = "select a.nick_name,a.head_img,b.id,b.unionid,b.dynamic_txt,b.dynamic_img,b.location,b.lat,b.lng,b.createtime,b.comments,b.praises from user a inner join star_dynamic b on a.unionid = b.unionid where b.id = " + id;

    app.exesql(sql, function (res) {
      var detail = res.data.data[0];
      detail.dynamic_txt = decodeURI(detail.dynamic_txt);
      if (detail.dynamic_img != null && detail.dynamic_img.length > 0)
        detail.imgarray = detail.dynamic_img.split(",");
      if (detail.comments != null && detail.comments.length > 0) {
        detail.commentArray = JSON.parse(decodeURI(detail.comments));
      } else {
        detail.commentArray = [];
      }

      if (detail.praises != null && detail.praises.length > 0) {
        detail.praiseArray = JSON.parse(detail.praises);
      } else {
        detail.praiseArray = [];
      }
      detail.createtime = _this.formatdate(detail.createtime);


      _this.setData({
        detail: detail
      });
    });


  },

  tocomment: function (event) {
    var _this = this;

    var repliername = event.currentTarget.dataset.repliername;
    var replierunionid = event.currentTarget.dataset.replierunionid;
    var sortid = event.currentTarget.dataset.sortid;
    if (null != repliername && null != replierunionid) {
      if (replierunionid == app.globalData.unionid) {
        wx.showActionSheet({
          itemList: ['删除我的评论'],
          success: function (res) {
            console.log(res.tapIndex)
            if (0 == res.tapIndex) {
              for (var x in _this.data.detail.commentArray) {
                if (_this.data.detail.commentArray[x].sortid == sortid) {
                  _this.data.detail.commentArray.splice(x, 1);
                  _this.uptcomment();
                  break;
                }
              }
            }
          },
          fail: function (res) {
            console.log(res.errMsg)
          }
        })
        return;
      }


      this.data.detail.replier = { name: repliername, unionid: replierunionid };
      this.data.detail.commenttag = '回复' + repliername;
    } else {
      this.data.detail.commenttag = '评论';
    }
    this.data.detail.commentflag = true;
    this.setData({
      detail: this.data.detail
    });
  },
  docomment: function (event) {
    var _this = this;
    console.log(event.detail.value);

    this.data.detail.commentflag = false;

    this.data.detail.commentArray.push({ sortid: this.data.detail.commentArray.length, commentor: { name: app.globalData.userInfo.nickName, unionid: app.globalData.unionid }, replier: this.data.detail.replier, commenttxt: event.detail.value });

    this.uptcomment();

    this.insertmsg({ msg_type: this.data.detail.replier != null ? 1 : 0, dynamic_id: this.data.detail.id, msg_unionid: app.globalData.unionid, status: 0, unionid: this.data.detail.replier != null ? this.data.detail.replier.unionid : this.data.detail.unionid, msg: event.detail.value });





  },
  insertmsg: function (msg) {
    var _this = this;

    var sql = "insert user_msg (msg_type,dynamic_id,msg_unionid,status,createtime,unionid,msg) values(" + msg.msg_type + "," + msg.dynamic_id + ",'" + msg.msg_unionid + "'," + msg.status + ",now(),'" + msg.unionid + "','" + encodeURI(msg.msg) + "')";

    console.log(sql);

    wx.request({
      url: 'https://www.dpsoft.top/db.jsp', //仅为示例，并非真实的接口地址
      method: 'POST',
      data: {
        sql: sql
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: res => {
        console.log(res.data);

        if ("ok" == res.data.status) {



        } else {
          wx.showToast({
            title: '失败，请重试',
            icon: 'success',
            duration: 2000
          });
        }
      }
    });
  },
  uptcomment: function () {
    var _this = this;
    var commentJson = JSON.stringify(this.data.detail.commentArray);
    commentJson = commentJson.replace("'", "\\'");
    var sql = "update star_dynamic set comments='" + encodeURI(commentJson) + "' where id = " + this.data.detail.id;

    console.log(sql);

    wx.request({
      url: 'https://www.dpsoft.top/db.jsp', //仅为示例，并非真实的接口地址
      method: 'POST',
      data: {
        sql: sql
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: res => {
        console.log(res.data);

        if ("ok" == res.data.status) {

          _this.setData({
            detail: this.data.detail
          });

        } else {
          wx.showToast({
            title: '失败，请重试',
            icon: 'success',
            duration: 2000
          });
        }
      }
    });
  },
  formatdate: function (createtime) {
    var createdate = new Date(createtime);
    var nowdate = new Date();
    var hour = createdate.getHours();
    var minute = createdate.getMinutes();

    var nowyear = nowdate.getFullYear();
    var nowmonth = nowdate.getMonth();
    var nowday = nowdate.getDate();

    var createyear = createdate.getFullYear();
    var createmonth = createdate.getMonth();
    var createday = createdate.getDate();

    if (nowyear == createyear) {
      if (nowmonth == createmonth) {
        if (nowday == createday) {
          return "今天 " + hour + ":" + minute;
        } else if ((nowday - createday) == 1) {
          return "昨天 " + hour + ":" + minute;
        } else if ((nowday - createday) == 2) {
          return "前天 " + hour + ":" + minute;
        } else {
          return createday + "日 " + hour + ":" + minute;
        }
      } else {
        return (createmonth + 1) + "月" + createday + "日 " + hour + ":" + minute;
      }
    } else {
      return createyear + "年" + (createmonth + 1) + "月" + createday + "日 " + hour + ":" + minute;
    }
  },
  nocomment: function (event) {
    var _this = this;
    setTimeout(function () {
      if (!_this.data.commentfocus) {

        console.log(event.detail.value);
        _this.data.detail.commentflag = false;
        _this.setData({
          detail: _this.data.detail
        });
      }
      _this.data.commentfocus = false;
    }, 100);
  },
  focuscomment: function () {
    var _this = this;
    this.data.commentfocus = true;
    setTimeout(function () {
      _this.data.commentfocus = false;
    }, 100);
  },
  onPraise: function (event) {
    var _this = this;

    var hasPraise = false;
    for (var x in this.data.detail.praiseArray) {
      if (app.globalData.unionid == this.data.detail.praiseArray[x].unionid) {
        hasPraise = true;
        this.data.detail.praiseArray.splice(x, 1);
        break;
      }
    }


    if (!hasPraise) {

      this.data.detail.praiseArray.push({ name: app.globalData.userInfo.nickName, unionid: app.globalData.unionid });

      this.insertmsg({ msg_type: 2, dynamic_id: this.data.detail.id, msg_unionid: app.globalData.unionid, status: 0, unionid: this.data.detail.unionid, msg: '' });

    }


    var praiseJson = JSON.stringify(this.data.detail.praiseArray);
    praiseJson = praiseJson.replace("'", "\\'");
    var sql = "update star_dynamic set praises='" + praiseJson + "' where id = " + this.data.detail.id;
    console.log(sql);

    wx.request({
      url: 'https://www.dpsoft.top/db.jsp', //仅为示例，并非真实的接口地址
      method: 'POST',
      data: {
        sql: sql
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: res => {
        console.log(res.data);

        if ("ok" == res.data.status) {

          _this.setData({
            detail: this.data.detail
          });

        } else {
          wx.showToast({
            title: '失败，请重试',
            icon: 'success',
            duration: 2000
          });
        }
      }
    });



  },

  onPreviewImg: function (e) {

    var imgindex = e.currentTarget.dataset.imgindex;
    var imgarray = this.data.detail.imgarray;
    var previewarray = [];
    for (var x in imgarray) {
      previewarray.push('http://www.dpsoft.top/' + imgarray[x]);
    }
    wx.previewImage({
      current: previewarray[imgindex], // 当前显示图片的http链接
      urls: previewarray // 需要预览的图片http链接列表
    })
  },
  openmap: function (e) {
    var lat = e.currentTarget.dataset.lat;
    var lng = e.currentTarget.dataset.lng;
    wx.navigateTo({ url: "/example/map/map?latitude=" + lat + "&longitude=" + lng });
  }


}
